package page

import (
	"context"
	"strconv"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/blog/model"
	"mall/service/blog/rpc/internal/svc"
	"mall/service/blog/rpc/internal/utils/errorhandler"
	"mall/service/blog/rpc/types/blog"

	"github.com/gosimple/slug"
	"github.com/volatiletech/null/v8"
	"github.com/zeromicro/go-zero/core/logx"
)

type CreatePageLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreatePageLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreatePageLogic {
	return &CreatePageLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreatePageLogic) CreatePage(in *blog.PageInfo) (*blog.BaseIDResp, error) {
	// logx.Infof("BackendCreatePost : %+v ", in)

	var pageSlug string
	var text string
	if in.Slug != nil {
		pageSlug = strings.TrimSpace(*in.Slug)

		if len(strings.TrimSpace(pageSlug)) == 0 {
			return nil, errorx.NewInvalidArgumentError("cms.pageSlugRequired")
		}

		filterMap := make(map[string]map[string][]any)
		filterMap[model.BlogPageColumns.PostName] = map[string][]any{
			"equalTo": {pageSlug},
		}
		_, count, err := l.svcCtx.Page.GetList(l.ctx, model.M{}, 0, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if count > 0 {
			return nil, errorx.NewAlreadyExistsError("cms.pageSlugAlreadyExists")
		}

		slug.Lowercase = false
		text = slug.Make(pageSlug)
	} else {
		return nil, errorx.NewInvalidArgumentError("cms.pageSlugRequired")
	}

	if in.Content == nil {
		return nil, errorx.NewInvalidArgumentError("cms.pageContentRequired")
	}

	tx, err := l.svcCtx.DB.BeginTx(l.ctx, nil)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	now := time.Now()
	page := &model.BlogPage{
		PostName:         pageSlug,
		PostDate:         now,
		PostModifiedDate: now,
	}

	if in.Title != nil && len(strings.TrimSpace(*in.Title)) > 0 {
		page.PostTitle = strings.TrimSpace(*in.Title)
	}
	if in.Excerpt != nil && len(strings.TrimSpace(*in.Excerpt)) > 0 {
		page.PostExcerpt = strings.TrimSpace(*in.Excerpt)
	}

	var visibility uint32
	if in.Visibility != nil && *in.Visibility > 0 {
		visibility = *in.Visibility
	}

	var status uint16
	var pendingStatus int32 // 审核后的状态
	if in.Status != nil {
		if *in.Status == uint32(globalkey.PostStatusPublish) { // 发布
			if visibility == globalkey.PostVisibilityPrivate {
				status = uint16(globalkey.PostStatusPrivate)
			} else {
				status = uint16(globalkey.PostStatusPublish)
			}
		} else { // 其他状态
			status = uint16(*in.Status)
			if visibility == globalkey.PostVisibilityPrivate {
				pendingStatus = globalkey.PostStatusPrivate
			} else {
				pendingStatus = globalkey.PostStatusPublish
			}
		}
		page.PostStatus = status
	} else {
		page.PostStatus = uint16(globalkey.PostStatusAutoDraft)
	}

	if in.CommentStatus != nil && *in.CommentStatus > 0 {
		page.CommentStatus = 1
	}
	if in.Sort != nil {
		page.MenuOrder = int(*in.Sort)
	} else {
		page.MenuOrder = int(9999)
	}
	if in.CreatedBy != nil {
		page.PostAuthorID = *in.CreatedBy
	}

	if visibility == globalkey.PostVisibilityPasswordProtected && in.Password != nil {
		page.PostPassword = strings.TrimSpace(*in.Password)
	}
	if len(text) > 0 {
		page.GUID = "/" + text
	}

	rel := &model.BlogPageRel{
		Detail: &model.BlogPageDetail{
			PostContent: *in.Content,
		},
		CategoryIds: in.CategoryIds,
		TagIds:      in.TagIds,
	}
	if in.ContentFiltered != nil {
		rel.Detail.PostContentFiltered = *in.ContentFiltered
	}

	if len(in.Meta) > 0 {
		for _, v := range in.Meta {
			if v.Key == nil || len(strings.TrimSpace(*v.Key)) == 0 {
				continue
			}

			if v.Value == nil || len(strings.TrimSpace(*v.Value)) == 0 {
				continue
			}

			rel.Meta = append(rel.Meta, &model.BlogPageMetum{
				MetaKey:   strings.TrimSpace(*v.Key),
				MetaValue: null.StringFrom(strings.TrimSpace(*v.Value)),
			})
		}
	}
	if pendingStatus > 0 {
		rel.Meta = append(rel.Meta, &model.BlogPageMetum{
			MetaKey:   "_pending_status",
			MetaValue: null.StringFrom(strconv.FormatInt(int64(pendingStatus), 10)),
		})
	}

	allMediaMap := make(map[string]string)
	if len(in.AllMedia) > 0 {
		for _, v := range in.AllMedia {
			if v.Id != nil && v.Url != nil && len(*v.Id) > 0 && len(*v.Url) > 0 {
				allMediaMap[*v.Id] = *v.Url
			}
		}
	}

	if len(in.NewMedia) > 0 {
		var thumbnailOrder uint
		var thumbnailId uint64
		var thumbnailUrl string
		for idx, v := range in.NewMedia {
			var url string
			if v.Url != nil && len(*v.Url) > 0 {
				url = *v.Url
			}
			if len(url) == 0 && v.Uri != nil && len(*v.Uri) > 0 {
				url = *v.Uri
			}
			if len(url) == 0 {
				continue
			}

			var thumbnail uint8
			if v.Thumbnail != nil && *v.Thumbnail > 0 {
				thumbnail = uint8(*v.Thumbnail)
			}
			var order uint
			if v.Order != nil {
				order = uint(*v.Order)
			} else {
				order = uint(idx) + globalkey.AttachmentOrderOffset
			}
			var altText string
			if v.AltText != nil && len(*v.AltText) > 0 {
				altText = *v.AltText
			}

			var meta []string
			if v.Name != nil && len(*v.Name) > 0 {
				meta = append(meta, "filename:"+*v.Name)
				if len(altText) == 0 {
					altText = *v.Name
				}
			}
			if v.MetaData != nil && len(*v.MetaData) > 0 {
				meta = append(meta, *v.MetaData)
			}
			if v.MimeType != nil && len(*v.MimeType) > 0 {
				meta = append(meta, "mimeType:"+*v.MimeType)
			}
			metaData := strings.Join(meta, ";")

			var mediaId uint64
			if v.Id != nil && len(*v.Id) > 0 {
				if i, err := strconv.ParseInt(*v.Id, 10, 64); err == nil {
					mediaId = uint64(i)
				}
			}

			media := &model.BlogAttachmentRelationship{
				AttachmentID:        mediaId,
				AttachmentThumbnail: thumbnail,
				AttachmentOrder:     order,
				AttachmentImageURL:  url,
				AttachmentImageAlt:  altText,
				AttachmentImageMeta: metaData,
			}

			if thumbnail == 0 && mediaId > 0 {
				if uri, ok := allMediaMap[*v.Id]; ok {
					media.AttachmentSource = uri
				}
			}

			rel.Media = append(rel.Media, media)

			if thumbnail > 0 && (len(thumbnailUrl) == 0 || thumbnailOrder > order) {
				thumbnailOrder = order
				thumbnailId = mediaId
				thumbnailUrl = url
			}
		}

		if len(thumbnailUrl) > 0 {
			rel.Meta = append(rel.Meta, &model.BlogPageMetum{
				MetaKey:   "_thumbnail_id",
				MetaValue: null.StringFrom(strconv.FormatInt(int64(thumbnailId), 10)),
			})
			rel.Meta = append(rel.Meta, &model.BlogPageMetum{
				MetaKey:   "_thumbnail_url",
				MetaValue: null.StringFrom(thumbnailUrl),
			})
		}
		rel.Meta = append(rel.Meta, &model.BlogPageMetum{
			MetaKey:   "_photo_count",
			MetaValue: null.StringFrom(strconv.FormatInt(int64(len(rel.Media)), 10)),
		})
	}

	err = l.svcCtx.Page.Insert(l.ctx, tx, page, rel)
	if err != nil {
		tx.Rollback()
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	tx.Commit()

	return &blog.BaseIDResp{
		Id:  page.ID,
		Msg: i18n.CreateSuccess,
	}, nil
}
